package com.inspectortime.webapp.inspector.scheduleRule;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.inspectortime.domain.Inspector;
import com.inspectortime.domain.ScheduleRule;

public class EditScheduleRuleController extends ScheduleRuleController {
	
	private static Log log = LogFactory.getLog(EditScheduleRuleController.class);

	public EditScheduleRuleController() {
		super();
	}
	
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		
		ScheduleRule scheduleRule = null;
		String originatingRuleId = request.getParameter("ruleId");
		if (!StringUtils.isBlank(originatingRuleId)) {
			String inspectorId = request.getParameter("inspectorId"); 
			Inspector inspector = repository.loadInspector(inspectorId);
			scheduleRule = inspector.getScheduleRuleById(originatingRuleId);
		} 
		
		return scheduleRule;
	}

	
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {
	
		log.debug("EditScheduleRuleController.onSubmit");
		ScheduleRule scheduleRule = (ScheduleRule) command;
		scheduleRule.save();
		
		ModelAndView mv = new ModelAndView(getSuccessView());
		if (scheduleRule.getStartDate() != null) {
			mv.addObject("start", buildUrlStartDate(scheduleRule.getStartDate()));
		}
		mv.addObject("msg", "addEditScheduleRule.rule.changed");
		mv.addObject("inspectorId", request.getParameter("inspectorId"));
		return mv;
		
	}
	
}
